﻿using System;
using System.Windows.Forms;
using Microsoft.Win32;
using Peepster.Core;
using Peepster.Infrastructure.Twitter;
using Peepster.Properties;

namespace Peepster
{
    public partial class SettingsView : Form
    {
        private readonly RegistryKey _startUpRegistryKey;

        public SettingsView()
        {
            InitializeComponent();
            _startUpRegistryKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
        }

        private void SettingsView_Load(object sender, EventArgs e)
        {
            checkBoxRunAtStartup.Checked = AppSettings.RunOnWindowsStartUp; //RunOnWindowsStartUp();
            textBoxTwitterUserName.Text = AppSettings.TwitterUserName; //AppSettings.TwitterUserName;
            textBoxTwitterPassword.Text = AppSettings.TwitterPassword; // AppSettings.TwitterPassword;

            textBoxShortcutKey.Text = AppSettings.ShortCutKey.ToString();

            comboBoxKeyShortcutKeyModifier.DataSource = Enum.GetValues(typeof (KeyModifiers));
            comboBoxKeyShortcutKeyModifier.SelectedIndex = comboBoxKeyShortcutKeyModifier.FindString(AppSettings.ShortcutModifier.ToString()); ;
        }

        private bool RunOnWindowsStartUp()
        {
            return _startUpRegistryKey.GetValue(Application.ProductName) != null;
        }

        private void SetRunOnWindowsStartUp()
        {
            if (checkBoxRunAtStartup.Checked)
                _startUpRegistryKey.SetValue(Application.ProductName, Application.ExecutablePath);
            else
                _startUpRegistryKey.DeleteValue(Application.ProductName, false);
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            if (!RequiredInformationEntered()) return;
            if (!CanValidateTwitterAccount()) return;
            if (!HotKeyIsAvailable()) return;

            //SetRunOnWindowsStartUp();

            AppSettings.RunOnWindowsStartUp = checkBoxRunAtStartup.Checked;
            AppSettings.TwitterUserName = textBoxTwitterUserName.Text;
            AppSettings.TwitterPassword = textBoxTwitterPassword.Text;
            AppSettings.ShortCutKey = (Keys)Enum.Parse(typeof(Keys), textBoxShortcutKey.Text, true);
            AppSettings.ShortcutModifier = (KeyModifiers)comboBoxKeyShortcutKeyModifier.SelectedValue;
            AppSettings.Save();
            
            //Settings.Default.TwitterUserName = textBoxTwitterUserName.Text;
            //Settings.Default.TwitterPassword = textBoxTwitterPassword.Text;
            //Settings.Default.ShortCutKey = (Keys) Enum.Parse(typeof (Keys), textBoxShortcutKey.Text, true);
            //Settings.Default.ShortcutModifier = (KeyModifiers) comboBoxKeyShortcutKeyModifier.SelectedValue;

            //Settings.Default.Save();
            //Settings.Default.Reload();

            DialogResult = DialogResult.OK;
            Close();
        }

        private bool HotKeyIsAvailable()
        {
            HotKey hotKey = null;
            try
            {
                var key = (Keys) Enum.Parse(typeof (Keys), textBoxShortcutKey.Text, true);
                var keyModifier = (KeyModifiers) comboBoxKeyShortcutKeyModifier.SelectedValue;

                if (key == AppSettings.ShortCutKey && keyModifier == AppSettings.ShortcutModifier) return true;

                hotKey = new HotKey(key, keyModifier, null);
            }
            catch (Exception)
            {
                MessageBox.Show(this, "Hotkey Already Registered, Please select a new hotkey.", "Hotkey Not Available.",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            finally
            {
                if (hotKey != null) hotKey.Dispose();
            }
            return true;
        }

        private bool CanValidateTwitterAccount()
        {
            ITwitterService twitterService = TwitterClientFactory.Create();

            if (twitterService.ValidateAccount(textBoxTwitterUserName.Text, textBoxTwitterPassword.Text)) return true;

            MessageBox.Show(this, "Invalid Account information.  Please try again.", "Authentication Error!",
                            MessageBoxButtons.OK, MessageBoxIcon.Error);
            return false;
        }

        private bool RequiredInformationEntered()
        {
            if (String.IsNullOrEmpty(textBoxTwitterUserName.Text) || (String.IsNullOrEmpty(textBoxTwitterPassword.Text)))
            {
                MessageBox.Show(this, "Please enter your twitter account information", "Required Settings Missing!");
                return false;
            }

            return true;
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void textBoxShortcutKey_KeyDown(object sender, KeyEventArgs e)
        {
            textBoxShortcutKey.Text = e.KeyData.ToString();
        }
    }
}